%%%-------------------------------------------------------------------
%%% @author linhaibo
%%% @copyright (C) 2018, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 10. 四月 2018 上午11:32
%%%-------------------------------------------------------------------
-module(hook_lib).
-author("linhaibo").
-include("vmq_server.hrl").
%% API
-export([md5_hex/1,
        get_redis1_config/0,
        get_redis2_config/0,
        get_apns_host/0,
        to_integer/1,
        publish/4,
        publish/5,
        subscribe/3]).
%非持久化  新消息数
-define(REDIS1CONFIG,{"10.25.54.6",  6379, "HpV64o0jruA8fQKL3OcRGmKXxkKJ2Kxj", 1000}).
%持久化   Token
-define(REDIS2CONFIG ,{"10.25.147.53", 6379, "HpV64o0jruA8fQKL3OcRGmKXxkKJ2Kxj", 1000}).

-define(APNS_HOST, "103.72.144.56").%%香港服务器tcp_lan_server
-define(APNS_PORT, 8800).
-define(APNS_AUTH_KEY,"mlyiZ28gybunzmZ").

md5_hex(S) ->
    Md5_bin = erlang:md5(S),
    Md5_list = binary_to_list(Md5_bin),
    lists:flatten(list_to_hex(Md5_list)).
list_to_hex(L) -> lists:map(fun(X) -> int_to_hex(X) end, L).
int_to_hex(N) when N < 256 -> [hex(N div 16), hex(N rem 16)].
hex(N) when N < 10          -> $0 + N;
hex(N) when N >= 10, N < 16 -> $a + (N - 10).


subscribe(SubscriberId,Topic,Qos) ->
    {ok,NewTopic} = vmq_topic:validate_topic(subscribe,Topic),
    vmq_reg:subscribe(true,  SubscriberId, [{NewTopic,Qos}]).

publish({MountPoint,_}=_SubscriberId,Topic,Payload,Qos,Retain) ->
    Msg  = #vmq_msg{
        msg_ref = vmq_mqtt_fsm_util:msg_ref(),
        routing_key = Topic,
        payload = Payload,
        retain = Retain,
        dup=false,
        qos=Qos,
        mountpoint=MountPoint,
        persisted=false,
        sg_policy=prefer_local
    },
    Reply = vmq_reg:publish(true,vmq_reg_trie,Msg),
    error_logger:info_msg("publish ~p",[Reply]).

publish({MountPoint,_}=_SubscriberId,Topic,Payload,Qos) ->
    publish({MountPoint,_}=_SubscriberId,[Topic],Payload,Qos,false).

get_redis1_config()->
    ?REDIS1CONFIG.

get_redis2_config()->
    ?REDIS2CONFIG.

get_apns_host() ->
    {?APNS_HOST, ?APNS_PORT, ?APNS_AUTH_KEY}.

to_integer(I) when is_binary(I) -> to_integer(binary_to_list(I));
to_integer(I) when is_integer(I) -> I;
to_integer(I) when is_list(I) ->
    case catch list_to_integer(I) of
        {'EXIT', _} -> 0;
        Int -> Int
    end;
to_integer(_) -> 0.